/**
 * @returns
 */
(function()
{
	var inputFun = function()
	{
		this.id = getRandId();
		// 当前模版名称
		this.curCaption = '';
		// 当前模版名称
		this.curTemplateName = '';
		// 当前模板
		this.curTemplateArray = null;
		this.curDefaultFieldList = '';
		// 获取文件成功后的回调函数
		this.curBackFunction = null;
		this.initData = null;
		// 上传文件并预览
		this.isPreView = true;
		this.notReadFromFile = false;
		var that = this;
		// 注册table
		if (!inputFun.prototype._list)
			inputFun.prototype._list = [];
		app.templete(this);
		this._setEvent();
	}
	// 根据html对象取得当前
	inputFun.prototype.getThis = function(obj)
	{
		var k = $(obj).parents('.logininputbox');
		if (k.length > 0)
		{
			return app.templete(k[0].id);
		}
		return null;
	}
	// 初始化对象
	inputFun.prototype._setEvent = function()
	{
		// 下面只执行一次
		if (inputFun.prototype._)
			return;
		inputFun.prototype._ = 1;
		// 单击设置模板的事件
		var that = this;
		$('body').on('click', '.inputtemplete #setinputtemplete', function()
		{
			var ta = that.getThis(this);
			if (!ta)
				return;
			var temp = $(this).attr('temp');
			ta._setExcelTemplate(function()
			{
				ta._getExcelTemplate(function(tempa)
				{
					if (tempa)
					{
						ta.curTemplateArray = tempa;
						ta._readExcelFile();
					}
				});
			});
		});
		$('body').on('change', '.inputtemplete .inputfile input', function()
		{
			var ta = that.getThis(this);
			ta._getFileContent(null, this);
		});
		$('body').on('click', '.inputtemplete #pasteData', function()
		{
			var ta = that.getThis(this);
			fullEdit('', function(text, fun)
			{
				fun(ta._pasteData(text));
			})
		});
		$('body').on('click', '.inputtemplete #jsonData', function()
		{
			var ta = that.getThis(this);
			fullEditArray(function(text)
			{
				ta._jsonData(text);
			})
		});
	}
	/**
	 * 读取电子表格文件，选择文件，回调一个数组（根据tempType确定键值名称）
	 */
	inputFun.prototype.readExcelFile = function(caption, tempname, defaultFieldList, fun, initData, notreadfromfile)
	{
		if (!tempname || !defaultFieldList || !fun)
		{
			return errorMsg('missingParameter tempname defaultFieldList or fun');
		}
		if (this.getFileContentlayerIndex)
		{
			layer.close(this.getFileContentlayerIndex);
			this.getFileContentlayerIndex = null;
		}
		if (!initData)
			initData = null;
		else
		{
			if (typeof initData == 'string')
			{
				try
				{
					initData = JSON.parse(initData);
				}
				catch (err)
				{
					layer.msg('data format error');
					initData = null;
				}
			}
			else if (typeof initData != 'object')
				initData = null;
		}
		this.initData = initData;
		this.curCaption = caption;
		this.curBackFunction = fun;
		this.curDefaultFieldList = defaultFieldList;
		this.notReadFromFile = !!notreadfromfile;
		// 模版换了,重新读取模版
		if (!this.curTemplateArray || tempname != this.curTemplateName)
		{
			var that = this;
			this.curTemplateName = tempname;
			this._getExcelTemplate(function(tempa)
			{
				that.curTemplateArray = tempa;
				that._readExcelFile();
			});
			return;
		}
		this._readExcelFile();
	}
	/**
	 * 转换
	 */
	inputFun.prototype.arrayToString = function(t, format)
	{
		if (!t || typeof t != 'object')
			return t;
		if (format)
		{
			t = this._arrayToStringRemoveJF(t);
			var s = JSON.stringify(t);
			var t = '    ';
			s = s.replace(/\{/g, '{\n' + t + t);
			s = s.replace(/\[/g, '[\n' + t);
			s = s.replace(/,/g, ' ,\n' + t + t);
			s = s.replace(/\}/g, '\n' + t + '}');
			s = s.replace(/\]/g, '\n]');
			s = s.replace(/:/g, ' : ');
			var re = RegExp(t + t + '{', 'g');
			s = this._arrayToStringRemoveJF(s);
			s = s.replace(RegExp(' : rownumber', 'g'), ':rownumber');
			s = s.replace(re, t + '{');
		}
		else
			var s = JSON.stringify(t);
		return s;
	}
	/**
	 * 去打掉特殊符号，a 表示去掉，a 为字符串 表示替换回来
	 */
	inputFun.prototype._arrayToStringRemoveJF = function(a)
	{
		var k = [];
		for (var i = 0; i <= 6; i++)
			k.push('.1.2389900_' + i + '_0099832.1.');
		if (typeof a == 'object')
		{
			for ( var i in a)
			{
				if (typeof a[i] == 'object')
					a[i] = this._arrayToStringRemoveJF(a[i]);
				else
				{
					var s = a[i] + ' ';
					s = s.replace(/\{/g, k[0]);
					s = s.replace(/\}/g, k[1]);
					s = s.replace(/\[/g, k[2]);
					s = s.replace(/\]/g, k[3]);
					s = s.replace(/\,/g, k[4]);
					s = s.replace(/\:/g, k[5]);
					s = s.replace(/\;/g, k[6]);
					s = s.replace(/\n/g, ' ');
					s = s.replace(/\r/g, ' ');
					s = s.replace(/\t/g, ' ');
					a[i] = s.trim();
				}
			}
			return a;
		}
		else
		{
			a = (a + ' ').trim();
			a = a.replace(RegExp(k[0], 'g'), '{');
			a = a.replace(RegExp(k[1], 'g'), '}');
			a = a.replace(RegExp(k[2], 'g'), '[');
			a = a.replace(RegExp(k[3], 'g'), ']');
			a = a.replace(RegExp(k[4], 'g'), ',');
			a = a.replace(RegExp(k[5], 'g'), ':');
			a = a.replace(RegExp(k[6], 'g'), ';');
			return a;
		}
	}
	/**
	 * 执行读电子表格数据，如果run参数没有带，用上次的参数
	 */
	inputFun.prototype._readExcelFile = function()
	{
		var that = this;
		this._getFileContent(function(t, backfun)
		{
			// 解析数据
			var re = that._jxobj(t);
			if (re === false)
			{
				errorMsg(app.w('login.msg.fileFormatError'));
				return;
			}
			if (that.isPreView)
			{
				that._getTempHtml(re)
			}
			else
			{
				if (!that.curBackFunction(re))
				{
					// 调用的最终程序没有提交成功，显示原始数据
					that._getTempHtml(re);
				}
				else if (backfun)
					backfun();
			}
		});
	}
	/**
	 * 取得模板文件
	 */
	inputFun.prototype._getExcelTemplate = function(backfun, businessId)
	{
		var that = this;
		if (!businessId)
		{
			app.selectBusiness(function(businessId)
			{
				that._getExcelTemplate(backfun, businessId)
			});
			return;
		}
		ajax.request('wtp.login.tools.getExcelTemplate', {
			name : that.curTemplateName,
			defaultFieldList : that.curDefaultFieldList,
			businessId : businessId,
		}, function(d, ad)
		{
			if (d.length > 0 && d[0].data && d[0].data[0])
			{
				d = d[0];
				d['rowOmission'] = !!d['rowOmission'];
				ddata = {};
				for (var i = 0; i < d.data.length; i++)
				{
					if (d.data[i].key)
					{
						ddata[i] = {
							cap : d.data[i].cap,
							key : d.data[i].key,
						}
					}
				}
				d.data = ddata;
				backfun(d);
			}
		});
	}
	/**
	 * 设置导入模版
	 */
	inputFun.prototype.setExcelTemplate = function(backfun, templateName, defaultFieldList)
	{
		if (templateName)
			this.curTemplateName = templateName;
		if (defaultFieldList)
			this.curDefaultFieldList = defaultFieldList;
		return this._setExcelTemplate(backfun);
	}
	/**
	 * 设置导入模版
	 */
	inputFun.prototype._setExcelTemplate = function(backfun, businessId)
	{
		var that = this;
		if (!businessId)
		{
			app.selectBusiness(function(businessId)
			{
				that._setExcelTemplate(backfun, businessId)
			});
			return;
		}
		var form = new formFun({
			'container' : '',
			'method' : 'wtp.login.tools.setExcelTemplate',
			'showmemo' : true,
			'preDealDataFun' : function(data)
			{
				if (data['saveToAllBusiness'] == 'yes')
				{
					form.options.confirm = app.w('login.msg.AreYouSureSaveToAllBusiness');
					form.options.timeout = 180000;
				}
				else
				{
					form.options.confirm = '';
					form.options.timeout = 0;
				}
				return data;
			},
			'loadDataFun' : function(backfun)
			{
				ajax.request('wtp.login.tools.getExcelTemplate', {
					name : that.curTemplateName,
					defaultFieldList : that.curDefaultFieldList,
					businessId : businessId,
				}, function(d, ad)
				{
					if (d.length > 0 && d[0].data && d[0].data[0])
					{
						d = d[0];
						d['rowOmission'] = d['rowOmission'] == 1 ? 'yes' : 'no';
						backfun(d);
					}
					else
					{
						backfun({
							name : that.curTemplateName,
							rowOmission : 'no'
						});
					}
					if (ad['saveToAllBusiness'])
					{
						$('#' + form.id + ' .fo-saveToAllBusiness div label:last').hide();
						$('#' + form.id + ' .fo-saveToAllBusiness div label:first input').attr("checked", "checked");
					}
				});
			},
			'paras' : {
				'businessId' : {
					inputtype : 'hidden',
					value : businessId,
				},
				'name' : {
					inputtype : '',
					readonly : true,
					caption : app.w('name'),
				},
				'starti' : {
					required : true,
					caption : app.w('starti'),
					memo : app.w('login.msg.starti'),
					inputtype : 'number'
				},
				'rowOmission' : {
					required : true,
					inputtype : 'select',
					valuelist : {
						'yes' : app.w('boolYes'),
						'no' : app.w('boolNo')
					},
					caption : app.w('rowOmission'),
					memo : app.w('login.msg.rowOmission'),
				},
				'data' : {
					inputtype : 'textarea',
					caption : app.w('TemplateHeader'),
					required : true,
					classname : 'single',
					readonly : true,
					dataformat : 'array',
					memo : app.w('login.msg.TemplateHeader'),
					btnfun : function(fun, value)
					{
						var ip = (new inputFun);
						ip.readExcelFile(app.w('edit'), '_setExcelTemplate_', 'key,cap,color,bold,frontsize', function(t)
						{
							fun(ip.arrayToString(t, true));
							return true;
						}, value, true);
					}
				},
				'saveToAllBusiness' : {
					inputtype : 'select',
					valuelist : {
						'yes' : app.w('boolYes'),
						'no' : app.w('boolNo'),
					},
					value : 'no',
					caption : app.w('saveToAllBusiness'),
					memo : app.w('login.msg.saveToAllBusiness'),
				},
			}
		});
		form.showLayer(app.w('setExcelTemplate'), backfun);
	}
	inputFun.prototype._jxobj = function(t)
	{
		var temp = this.curTemplateArray;
		if (!temp)
			return false;
		if (!t.SheetNames || !t.SheetNames[0])
			return false;
		var Sheet1name = t.SheetNames[0];
		var Sheet1 = t.Sheets[Sheet1name];
		if (!Sheet1)
			return false;
		var a = [];
		var hangarr = {};
		var rowi = 0;
		for ( var k in Sheet1)
		{
			var rc = getrowcol(k);
			if (rc.lie < 0 || rc.hang < 0 || rc.hang + 1 < temp.starti)
			{
				continue;
			}
			if (temp.data[rc.lie])
			{
				var key = temp.data[rc.lie]['key'];
			}
			else
				continue;
			var r = rowi;
			// 出现了新行
			if (hangarr[rc.hang] !== 0 && !(hangarr[rc.hang] > 0))
			{
				hangarr[rc.hang] = rowi;
				rowi++;
				a[r] = {
					':rownumber' : rc.hang + 1
				};
			}
			else
				r = hangarr[rc.hang];
			if (!Sheet1[k]['w'] && Sheet1[k]['v'])
				a[r][key] = Sheet1[k]['v'];
			else
				a[r][key] = Sheet1[k]['w'];
		}
		// 处理空缺数据
		for (var r = 0; r < a.length; r++)
		{
			for ( var j in temp.data)
			{
				var key = temp.data[j].key;
				if (a[r][key] === undefined)
					a[r][key] = '';
				if (temp.rowOmission && a[r][key] === '' && r > 0)
				{
					a[r][key] = a[r - 1][key];
				}
			}
		}
		return a;
		function getrowcol(k)
		{
			var s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			var rc = {
				lie : -1, // 列
				hang : -1
			// 行
			};
			for (var i = 0; i < k.length; i++)
			{
				var j = s.indexOf(k[i]);
				if (j < 0)
					return rc;
				else if (j < 26)
				{
					// 列
					if (rc.lie < 0)
						rc.lie = j;
					else
						rc.lie = (rc.lie + 1) * 26 + j;
				}
				else
				{
					var v = parseInt(k.substring(i, i + 8));
					if (isNaN(v))
						return rc;
					rc.hang = v - 1;
					return rc;
				}
			}
			return rc;
		}
	}
	/**
	 * 粘贴数据
	 */
	inputFun.prototype._pasteData = function(text, backfun)
	{
		var fun = this.getFileContentFunction;
		var v = XLSX.read(text, {
			type : "binary"
		});
		fun(v, backfun);
	}
	/**
	 * JSON 格式数据粘贴
	 */
	inputFun.prototype._jsonData = function(text, backfun)
	{
		var fun = this.getFileContentFunction;
		try
		{
			var v = JSON.parse(text);
		}
		catch (err)
		{
			var v = [];
		}
		if (v)
		{
			this._getTempHtml(v);
		}
	}
	/**
	 * 取得文件内容
	 */
	inputFun.prototype._getFileContent = function(fun, obj, notload)
	{
		var that = this;
		if (typeof XLSX == 'undefined')
		{
			if (!notload)
			{
				loadJs(app.core+'/js/plugins/xlsx/xlsx.core.min.js', function()
				{
					that._getFileContent(fun, obj, true);
				});
			}
			return;
		}
		if (!obj)
		{
			if (!this.getFileContentFunction)
			{
				this.getFileContentFunction = fun;
				var html = this._getHtml();
				if (html)
					this.getFileContentlayerIndex = showFullLayer(this.curCaption ? this.curCaption : app.w('selectFile'), html);
			}
			else
			{
				var html = this._getHtml(true);
				$('#' + this.id).html(html);
				this._getTempHtml();
			}
		}
		else
		{
			fun = this.getFileContentFunction;
			if (!$(obj).val())
				return;
			var filename = $(obj).val();
			var ext = filename.substr(filename.lastIndexOf(".") + 1);
			if ((",,txt,csv,xls,xlsx,xlsm,xltx,xltm,xlsb,xlam,,").indexOf(',' + ext + ',') < 0)
			{
				errorMsg(app.w('login.msg.fileTypeError') + ' : ' + ext);
				$(obj).val('');
				return;
			}
			$('#' + this.id + ' #uploadeFileName').html('<b> &nbsp; &nbsp; &nbsp; &nbsp; ' + app.w('uploadeFileName') + '</b> : ' + filename);
			var file = document.getElementById("uploadInput").files[0];
			this.isPreView = false;
			if (!file)
			{
				file = document.getElementById("uploadInput2").files[0];
				this.isPreView = true;
			}
			var reader = new FileReader(file);
			// 将文件以二进制形式读入页面
			reader.readAsBinaryString(file);
			var that = this;
			reader.onload = function()
			{
				var v = XLSX.read(this.result, {
					type : "binary"
				});
				fun(v, function()
				{
					layer.close(that.getFileContentlayerIndex)
				});
				$(obj).val('');
				delete reader;
			}
		}
	}
	inputFun.prototype._getHtml = function(noBox)
	{
		var that = this;
		var temp = this.curTemplateArray;
		if (!temp)
			return;
		if (!this.boxid)
			this.boxid = getRandId();
		var accept = '.txt,.csv,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
		var html = '';
		if (!noBox)
			html += '<div class="readExcelFileBox logininputbox" id="' + this.id + '">';
		html += '<div class="excel" id="' + this.boxid + '"></div>';
		if (!this.notReadFromFile)
		{
			html += '<p style="margin:0"><span id="uploadeFileName"></span>';
			html += '<div class="inputtemplete">';
			html += ' &nbsp; &nbsp; <b>' + app.w('inputDataFromExcel') + '</b> [ ' + app.w('login.msg.starti') + ' : ' + temp.starti;
			// html += ' &nbsp; ' + app.w('login.msg.rowOmission') + ' : ' + (temp.rowOmission ? app.w('boolYes') : app.w('boolNo'));
			html += ' ] &nbsp; &nbsp; <a id="setinputtemplete" temp="' + temp.name + '" >' + app.w('editTemplete') + '</a>';
			html += ' <span class="inputfile"><input capture0="camera/video/*" accept="' + accept + '" type="file" id="uploadInput"><a>' + app.w('upLoadFileAndSubmit') + '</a></span>';
			html += ' <span class="inputfile"><input capture0="camera/video/*" accept="' + accept + '" type="file" id="uploadInput2"><a>' + app.w('uploadFileAndPreview') + '</a></span>';
			html += ' &nbsp; &nbsp; <a id="pasteData">' + app.w('paste') + '</a> ';
			html += ' &nbsp; &nbsp; <a id="jsonData">JSON</a> ';
			html += '</div>';
		}
		if (!noBox)
			html += '</div>';
		if ($('#' + this.id + ' .readExcelFileBox').html())
		{
			$('#' + this.id + ' .readExcelFileBox').html(html);
			return null;
		}
		setTimeout(function()
		{
			that._getTempHtml();
		}, 100);
		return html;
	}
	inputFun.prototype._getTempHtml = function(data)
	{
		var that = this;
		var temp = this.curTemplateArray;
		if (!temp)
			return;
		var dataheader = {};
		var ix = 0;
		var ll = 0;
		for ( var i in temp.data)
		{
			var ii = parseInt((i + ' ').trim());
			if (ix < ii)
			{
				for (var iii = ix; iii < ii; iii++)
				{
					dataheader['_none_' + i] = '<font class="hui">[' + this._gethead0(i - 1) + ']</font>';
					ll++;
				}
			}
			var key = temp.data[i]['key'];
			var cap = temp.data[i]['cap'];
			if (!cap)
				cap = key;
			dataheader[key] = [ cap ];
			ll++;
			ix = ii + 1;
			if (ix > 260)
				break;
		}
		if (!data)
			data = this.initData;
		new excelFun('', dataheader, data, function(data)
		{
			if (that.curBackFunction(data, that.getFileContentlayerIndex))
				layer.close(that.getFileContentlayerIndex);
		}, this.boxid, this.notReadFromFile ? 0 : -2, temp.starti);
	}
	inputFun.prototype._gethead0 = function(i)
	{
		var k = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ];
		if (i < 26)
			return k[i];
		else if (i <= 260)
			return k[Math.floor(i / 26) - 1] + k[i - (Math.floor(i / 26)) * 26];
		return '';
	}
	window.inputFun = inputFun;
}());
/**
 * 以下是电子表格控件
 * 
 * @returns
 */
(function()
{
	/**
	 * 模拟简单的电子表格功能,对一个数组进行编辑,并支持数据电子表格导入
	 */
	var excelFun = function(caption, options, data, backfun, boxid, addpagesize, starti)
	{
		this.backfun = backfun;
		this.id = getRandId();
		this.caption = caption;
		this.page = 1;
		this.layerIndex = null;
		this.pagesize = 10;
		if (!data)
			data = [];
		this.data = data;
		this.starti = starti ? starti : 1;
		this.addpagesize = addpagesize ? addpagesize : 0;
		this.options = $.extend({
			// 直接输入各字段的头
			_no_ : [ ' ', '1%' ],
		// k2 : ['KK1', '23%', 'date', 'fa-edit'] // caption 和 inputtype
		// k3 : 'KK3',
		}, options);
		this._show(boxid);
	};
	excelFun.prototype._inputData = function(index, ki, oldvalue, value)
	{
		index = (this.page - 1) * this.pagesize + index;
		for (var i = this.data.length; i <= index; i++)
		{
			this.data[i] = {};
			for ( var k in this.options)
			{
				var cap = this.options[k];
				this.data[i][k] = '';
				this.data[i]['_no_'] = i + 1;
			}
		}
		this.data[index][ki] = value;
	}
	excelFun.prototype._createTable = function()
	{
		// 创建表，返回表体html
		var that = this;
		var table = null;
		var datai = {};
		var header = {};
		for ( var k in this.options)
		{
			var cap = this.options[k];
			datai[k] = '';
			if (typeof cap == 'string' || k == '_no_')
			{
				header[k] = cap;
				if (k == '_no_')
					header[k][3] = 'thtdno';
			}
			else
			{
				if (k != '_op_' && k != '_mu_')
				{
					header[k] = cap;
					header[k][4] = function(index, k, oldvalue, value)
					{
						that._inputData(index, k, oldvalue, value);
					};
				}
			}
		}
		header['_op_'] = [ {
			title : app.w('del'),
			icon : 'fa-trash-o',
			_mu_ : true,
			fun : function(index, idi, data)
			{
				index = (that.page - 1) * that.pagesize + index;
				that.data.splice(index, 1);
				table.setData();
			}
		}, {
			title : app.w('add'),
			icon : 'fa-plus',
			_mu_ : true,
			fun : function(index, idi, data)
			{
				index = (that.page - 1) * that.pagesize + index;
				that.data.splice(index, 0, {});
				table.setData();
			}
		}, ];
		table = new tableFun({
			container : '',
			showpage : true,
			showheader : true,
			refreshbtn : false,
			addpagesize : this.addpagesize,
			okFun : function()
			{
				var starti = 2;
				var temp = that.curTemplateArray;
				if (temp && temp.starti)
					starti = temp.starti;
				if (that.backfun)
				{
					var d = [];
					for (var i = 0; i < that.data.length; i++)
					{
						var dobj = {
							':rownumber' : i + starti,
						};
						var have = false;
						for ( var k in that.data[i])
						{
							if (k != '_no_' && k.indexOf('_none_') !== 0 && k.indexOf(':rownumber') !== 0)
							{
								var v = that.data[i][k]
								dobj[k] = v;
								if (v !== '')
									have = true;
							}
						}
						if (have)
						{
							d.push(dobj);
						}
					}
					that.backfun(d);
					if (that.layerIndex)
						layer.close(that.layerIndex);
				}
			},
			loadDataFun : function(page, fun, searchpara)
			{
				if (!page)
					page = 1;
				var pagesize = table.getPageSize();
				var d = [];
				for (var i = 0; i < pagesize; i++)
				{
					d[i] = {};
					for ( var k in datai)
						d[i][k] = datai[k];
					var ii = (page - 1) * pagesize + i;
					if (that.data.length > ii)
					{
						for ( var k in that.data[ii])
							d[i][k] = that.data[ii][k];
					}
					d[i]['_no_'] = ii + that.starti;
				}
				that.page = page;
				that.pagesize = pagesize;
				fun(d, page + 1);
			},
			'header' : header,
		});
		return table.html;
	}
	// 显示出来
	excelFun.prototype._show = function(boxid)
	{
		if (!boxid)
		{
			var caption = this.caption ? this.caption : app.w('edit');
			this.layerIndex = showFullLayer(caption, this._createTable());
		}
		else
			$('#' + boxid).html(this._createTable());
	}
	window.excelFun = excelFun;
}());
